package com.caiyifan.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    Map<String, String> userMap = new HashMap<String, String>(16);
    {
        userMap.put("realm","32c1ecaeab37eb90055cd45fcbbec527");
        userMap.put("tom","32c1ecaeab37eb90055cd45fcbbec527");
        super.setName("customRealm1");
    }

    // 授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();

        Set<String> roles = getRolesByUserName(username);

        Set<String> permissions = getPermissionByUserName(username);

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(roles);
        simpleAuthorizationInfo.setStringPermissions(permissions);


        return simpleAuthorizationInfo;
    }

    private Set<String> getRolesByUserName(String username){

        // 从数据库或缓存中获取角色
        Set<String> sets = new HashSet<String>(16);
        sets.add("admin");
        sets.add("user");

        return sets;
    }

    private Set<String> getPermissionByUserName(String username){
        // 从数据库或缓存中获取用户角色
        Set<String> sets = new HashSet<String>(16);
        sets.add("user:delete");
        sets.add("user:add");

        return sets;
    }

    // 认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 1 从主体传过来的认证信息中获取用户名
        String username = (String) authenticationToken.getPrincipal();

        // 2 通过用户名到数据库中获取凭证
        String password = getPasswordByUserName(username);

        if (password == null){
            return null;
        }

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password, "customRealm1");

        // "盐"设置
        simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("realm"));
        return simpleAuthenticationInfo;
    }

    private String getPasswordByUserName(String username){
        // 查数据库,获取密码
        return userMap.get(username);
    }

    public static void main(String[] args) {
        // md5加盐
        Md5Hash md5Hash = new Md5Hash("123456","realm");
        System.out.println(md5Hash.toString());
    }
}
